<template>
  <view class="container">
    <view class="header">
      <text class="title">用户登录</text>
    </view>
    
    <view class="input-group">
      <text class="input-label">手机号</text>
      <input class="input-field" v-model="tel" type="text" placeholder="请输入手机号" />
    </view>
    
    <view class="input-group">
      <text class="input-label">密码</text>
      <input class="input-field" v-model="password" type="password" placeholder="请输入密码" />
    </view>
    
    <button class="btn" @click="handleLogin">登录</button>
    
    <text class="link" @click="navigateToRegister">还没有账号？立即注册</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tel: '',
      password: ''
    }
  },
  methods: {
    handleLogin() {
      if (!this.tel || !this.password) {
        uni.showToast({
          title: '请输入手机号和密码',
          icon: 'none'
        });
        return;
      }
	  
	  uni.showLoading({
		title: '登录中...'
	  });
      
      uni.request({
        url: 'http://192.168.1.42:8000/api/auth.php?action=login',
        method: 'POST',
        data: {
          tel: this.tel,
          password: this.password
        },
        success: (res) => {
			uni.hideLoading();
          if (res.data.error) {
            uni.showToast({
              title: res.data.message,
              icon: 'none'
            });
          } else {
            // 登录成功，保存用户信息到本地存储
				uni.setStorageSync('user', res.data.user);
				uni.setStorageSync('userId', res.data.user.id); // 确保存储了userId
				uni.showToast({
                    title: '登录成功',
                    icon: 'success',
                    duration: 1500,
					success: () => {
						// 使用redirectTo跳转
						uni.switchTab({
							url: '/pages/index/index',
							fail: (err) => {
								console.error('redirectTo失败:', err);
								// 如果redirectTo失败，使用navigateTo
								uni.navigateTo({
									url: '/pages/index/index'
								});
							}
                        });
                    }
                });
            }
        },
        fail: (err) => {
		  uni.hideLoading();
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    navigateToRegister() {
      uni.navigateTo({
        url: '/pages/user/register'
      });
    }
  }
}
</script>

<style>
.header {
  margin-bottom: 30px;
  text-align: center;
}
.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}
</style>